package com.buss.product.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.buss.base.model.DicData;
import com.buss.base.service.DicDataService;
import com.buss.core.controller.BaseController;
import com.buss.core.dic.RecordStatus;
import com.buss.core.exception.ServiceException;
import com.buss.core.exception.WebException;
import com.buss.core.persistence.OrderBy;
import com.buss.core.persistence.Pagination;
import com.buss.core.persistence.ResultList;
import com.buss.core.sysparam.SysStaticParam;
import com.buss.core.utils.StringUtil;
import com.buss.product.model.Brand;
import com.buss.product.model.CateProp;
import com.buss.product.model.CateProp.PropEntryWay;
import com.buss.product.model.CateProp.PropSelectType;
import com.buss.product.model.CatePropGroup;
import com.buss.product.model.Goods;
import com.buss.product.model.GoodsCategory;
import com.buss.product.model.GoodsDetail;
import com.buss.product.model.GoodsProp;
import com.buss.product.service.BrandService;
import com.buss.product.service.CatePropGroupService;
import com.buss.product.service.CatePropService;
import com.buss.product.service.GoodsCategoryService;
import com.buss.product.service.GoodsDetailService;
import com.buss.product.service.GoodsService;
import com.buss.product.utils.ProductStaticParam;

@Controller
@RequestMapping("/admin/goods/")
public class GoodsController extends BaseController {

	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsCategoryService categoryService;
	
	@Autowired
	private BrandService brandService;
	
	@Autowired
	private DicDataService dicDataService;
	
	@Autowired
	private CatePropGroupService propGroupService;
	
	@Autowired
	private CatePropService propService;
	
	@Autowired
	private GoodsDetailService detailService;
	
	@Override
	@RequestMapping("page")
	public ModelAndView listPage(String menuid) {
		ModelAndView view = new ModelAndView("goods/listpage");
		view.addObject(SysStaticParam._MENUID_NAME, menuid);
		return view;
	}

	@RequestMapping("selectgoods")
	public String selectGoodsPage(){
		return "goods/selectgoods";
	}
	
	@RequestMapping("selectgoodsdetail")
	public String selectGoodsDetailPage(){
		return "goods/selectgoodsdetail";
	}
	
	@RequestMapping("{type}")
	public ModelAndView editPage(@PathVariable String type, Long id,HttpServletRequest request) {
		Long categoryId = 0L;
		ModelAndView view = new ModelAndView("goods/edit");
		Goods goods = new Goods();
		GoodsCategory category = null;
		List<Brand> brands = null;
		OrderBy orderBy = new OrderBy();
		orderBy.add("orderSort", OrderBy.ASC);
		List<Long> groupIds = new ArrayList<Long>();
		List<DicData> dicDatas = dicDataService.queryDicData(getCompanyId(request), ProductStaticParam.PRODUCT_UNIT_CODE, null, orderBy).getData();
		if(EDIT_PAGE.equals(type)){
			goods = goodsService.loadGoods(id);
			categoryId = goods.getCategory().getId();
			brands = brandService.queryBrand(goods.getCategory().getId()).getData();
		}else{
			categoryId = id;
			category = categoryService.loadCategory(id);
			goods.setCategory(category);
			goods.setIsFixed(false);
			goods.setStatus(RecordStatus.normal);
			if(!category.getBranchId().equals("0")){
				goods.setBranchId(","+getBranchId(request).toString() + ",");
			}else{
				goods.setBranchId("0");
			}
			brands = brandService.queryBrand(id).getData();
		}
		orderBy = new OrderBy();
		orderBy.add("sortOrder", OrderBy.ASC);
		List<CatePropGroup> propGroups = propGroupService.queryCatePropGroupByParentCategoryId(getCompanyId(request), categoryId, RecordStatus.normal, orderBy, null).getData();
		
		for(CatePropGroup group : propGroups){
			groupIds.add(group.getId());
			group.setProps(propService.queryProp(group.getId(), null, null, RecordStatus.normal, orderBy, null).getData());
		}
		Long[] gIds = new Long[groupIds.size()];
		groupIds.toArray(gIds);
		
		view.addObject("goods", goods);
		view.addObject("brands",brands);
		view.addObject("dicDatas",dicDatas);
		view.addObject("propGroups",propGroups);
		return view;
	}

	
	
	/**
	 * 新增商品信息
	 * @param goods
	 * @param request
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public Map<String,Object> add(Goods goods,HttpServletRequest request) throws WebException{
		editGoods(goods, request, true);
		Map<String, Object> map = SysStaticParam.resultMessage("新增商品信息成功!");
		map.put("goods", goods);
		return map;
	}
	
	/**
	 * 修改商品信息
	 * @param goods
	 * @param request
	 * @return
	 */
	@RequestMapping("edit")
	@ResponseBody
	public Map<String,Object> edit(Goods goods,HttpServletRequest request) throws WebException {
		editGoods(goods, request, false);
		return SysStaticParam.resultMessage("修改商品信息成功!");
	}

	/**
	 * 新增、修改商品信息
	 * @param goods
	 * @param request
	 * @param isAdd
	 * @throws WebException
	 */
	private void editGoods(Goods goods,HttpServletRequest request,boolean isAdd) throws WebException{
		List<CatePropGroup> propGroups = propGroupService.queryCatePropGroupByParentCategoryId(getCompanyId(request), goods.getCategory().getId(), RecordStatus.normal, null, null).getData();
		List<GoodsProp> goodsProps = new ArrayList<GoodsProp>();
		Map<String, Object> extProp = new HashMap<String, Object>();
		for(CatePropGroup group : propGroups){
			List<CateProp> props = propService.queryProp(group.getId(), null, null, RecordStatus.normal, null, null).getData();
			for(CateProp prop : props){
				
				GoodsProp goodsProp = new GoodsProp();
				goodsProp.setCateProp(prop);
				if(prop.getSelectType().equals(PropSelectType.uniqueProp)){
					if(prop.getEntryWay().equals(PropEntryWay.manualWay)){						
						goodsProp.setPropValue(request.getParameter(prop.getCode()));
						extProp.put(prop.getCode(), request.getParameter(prop.getCode()));
					}
					if(prop.getEntryWay().equals(PropEntryWay.listChoice) || prop.getEntryWay().equals(PropEntryWay.dicChoice)){
						String[] values = (String[])request.getParameterValues(prop.getCode());
						goodsProp.setPropValueArr(values);
						extProp.put(prop.getCode(), StringUtil.join(values, "\n"));
					}
				}
				if(prop.getSelectType().equals(PropSelectType.singleChoice) || prop.getSelectType().equals(PropSelectType.multichoice)){
					String[] values = (String[])request.getParameterValues(prop.getCode());
					goodsProp.setPropValueArr(values);
				}
				if(prop.getSelectType().equals(PropSelectType.multichoice)){
					String[] values = (String[])request.getParameterValues(prop.getCode());
					extProp.put(prop.getCode(), StringUtil.join(values, "\n"));
				}
				goodsProp.setGoods(goods);
				goodsProps.add(goodsProp);
			}
		}
		ObjectMapper mapper = new ObjectMapper();
		String extP = "";
		try {
			extP = mapper.writeValueAsString(extProp);
			goods.setExtProp(extP);
		} catch (Exception e) {
			throw new WebException(e.getMessage());
		} 
		goods.setProps(goodsProps);
		goods.getCategory().setCompanyId(getCompanyId(request));
		List<GoodsDetail> details = new ArrayList<GoodsDetail>();
		String[] detailValues = (String[])request.getParameterValues("product_details");
		String[] detailTitles = (String[])request.getParameterValues("product_details_title");
		String[] productBarcode = (String[]) request.getParameterValues("barCode");
		String[] productPrices = (String[]) request.getParameterValues("product_price");
		String[] pIds = (String[])request.getParameterValues("product_pIds");
		if(detailValues != null && detailValues.length > 0){
			int length = detailValues.length;
			for(int i = 0;i < length;i++){
				GoodsDetail detail = new GoodsDetail();
				detail.setBarCode(productBarcode[i]);
				detail.setPrice(Float.parseFloat(productPrices[i]));
				detail.setId(StringUtil.isEmpty(pIds[i]) ? null : Long.parseLong(pIds[i]));
				detail.setGoods(goods);
				detail.setPropContext(detailValues[i]);
				detail.setPropContextValue(detailTitles[i]);
				details.add(detail);
			}			
		}else{
			GoodsDetail detail = new GoodsDetail();
			detail.setBarCode(productBarcode[0]);
			detail.setPrice(Float.parseFloat(productPrices[0]));
			detail.setId((pIds == null || StringUtil.isEmpty(pIds[0])) ? null : Long.parseLong(pIds[0]));
			detail.setGoods(goods);
			detail.setPropContext("");
			details.add(detail);
		}
		goods.setDetails(details);
		try{
			if(isAdd){
				goods = goodsService.saveGoods(goods);
			}else{
				goodsService.editGoods(goods);
			}
		}catch(ServiceException ex){
			throw new WebException(ex.getMessage());
		}
	}
	
	
	/**
	 * 获取商品信息列表
	 * @param categoryIds
	 * @param name
	 * @param pinyin
	 * @param brandId
	 * @param status
	 * @param orderFiled
	 * @param orderType
	 * @param page
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(Long[] categoryIds,String name,String pinyin,Long brandId,String styleNo,
			RecordStatus status,String orderField,String orderType, Pagination page,
			HttpServletRequest request){
		OrderBy orderBy = null;
		if(StringUtil.isNotEmpty(orderField) && StringUtil.isNotEmpty(orderType)){
			orderBy = new OrderBy();
			orderBy.add(orderField, orderType);
		}
		List<GoodsCategory> categorys = categoryService.queryCategoryByParentId(getCompanyId(request),getBranchId(request).toString(), categoryIds[0]);
		Long[] tmpIds = new Long[categorys.size() + 1];
		tmpIds[0] = categoryIds[0];
		for(int i = 0;i < categorys.size();i++){
			tmpIds[i + 1] = categorys.get(i).getId();
		}
		ResultList<Goods> rs = goodsService.queryGoods(tmpIds, name, pinyin, brandId, getBranchId(request).toString(),styleNo, status, orderBy, page);
		Map<String, Object> map = SysStaticParam.resultMessage("获取商品信息成功!");
		map.put(SysStaticParam._RESULT, rs);		
		return map;
	}
	
	/**
	 * 根据商品ID获取商品详情
	 * @param goodsId
	 * @return
	 */
	@RequestMapping("list/{goodsId}")
	@ResponseBody
	public Map<String, Object> queryGoodsDetail(@PathVariable Long goodsId){
		ResultList<GoodsDetail> rs = detailService.queryGoodsDetail(goodsId);
		Map<String, Object> map = SysStaticParam.resultMessage("获取商品信息成功!");
		map.put(SysStaticParam._RESULT, rs);
		return map;
	}
	
	/**
	 * 根据商品条码查询商品信息
	 * @param barCode
	 * @param request
	 * @return
	 */
	@RequestMapping("querybybarcode")
	@ResponseBody
	public Map<String,Object> queryGoodsDetailByBarcode(String barCode,HttpServletRequest request){
		ResultList<GoodsDetail> rs = detailService.queryGoodsDetailByBarcode(getCompanyId(request), getBranchId(request).toString(), barCode);
		Map<String, Object> map = SysStaticParam.resultMessage("获取商品信息成功!");
		map.put(SysStaticParam._RESULT, rs);
		return map;
	}
	
	@Override
	@RequestMapping("delete")
	@ResponseBody
	public Map<String, Object> delete(Long[] ids){
		goodsService.removeGoods(ids);
		return SysStaticParam.resultMessage("删除商品信息成功!");
	}

	@Override
	public ModelAndView editPage(String type, Long id) {
		return null;
	}

	/**
	 * 用于处理有销售属性商品信息
	 * @param a
	 * @param b
	 * @return
	 */
	private boolean register(String[][] a,int[] b){
		int s = b.length;
		for(int i = b.length - 1;i >= 0;--i){
			if(b[i] + 1 < a[i].length){
				b[i] = b[i] + 1;
				return true;
			}else if(i - 1 >= 0){
				b[i] = 0;
			}else{
				return false;
			}
		}
		return false; 	
	}
	
}
